
const vscode = (window as any).acquireVsCodeApi();

class SgsSiderwebview {
    constructor() {
        this.initUi()
        vscode.postMessage({ type: 'checkActive' })
    }
    initUi() {
        this.createMenuItem('新建文档', this.newDocument)
        this.createMenuItem('导出源码', this.exportDocument)
        this.createMenuItem('添加节点', this.openNodeSelector)
        this.createMenuItem('运行项目', this.excuteDocument)

        window.addEventListener('message', this.messageHandler.bind(this))
    }
    private messageHandler(event: MessageEvent) {
        switch(event.data.type) {
            case 'setActive':
                this.setActive(event.data.data)
                break
        }
    }
    private setActive(active: boolean) {
        const menus = document.querySelector('#sider-menus') as HTMLElement
        const welcome = document.querySelector('#welcome-box') as HTMLElement
        if(active) {
            menus.style.display = 'flex'
            welcome.style.display = 'none'
        }else{
            menus.style.display = 'none'
            welcome.style.display = 'block'
        }
    }
    private createMenuItem(label: string, callBack: () => void) {
        const button = document.createElement('button')
        button.className = 'com-btn com-btn-block'
        button.textContent = label
        button.onclick = callBack
        document.querySelector('#sider-menus')?.appendChild(button)
    }
    newFile() {
        vscode.postMessage({ type: 'newFile' })
    }
    newDocument() {
        vscode.postMessage({ type: 'newDoc' })
    }

    exportDocument() {
        vscode.postMessage({ type: 'compileCode' })
    }

    excuteDocument() {
        vscode.postMessage({ type: 'executeCode' })
    }

    openNodeSelector() {
        vscode.postMessage({ type: 'nodeSelector' })
    }
}